<?php


namespace App\Utils;


use Illuminate\Support\Arr;

class ManyDataHandler
{
    public $query;
    public $keys = [];
    public $data = [];
    public $keyField = 'id';

    public function __construct($query)
    {
        $this->query = $query;
    }

    static function get($query): self
    {
        return new static($query);
    }

    public function add($id): self
    {
        $this->keys[$id] = 1;
        return $this;
    }

    public function adds($ids): self
    {
        foreach ($ids as $id) {
            $this->keys[$id] = 1;
        }
        return $this;
    }

    public function query($fields = []): array
    {
        $ids = array_keys($this->keys);
        if (count($ids)) {
            if (count($fields)) {
                $this->query->select($fields);
            }
            $data = $this->query->whereIn($this->keyField, array_keys($this->keys))->get();
            $this->data = [];
            foreach ($data as $datum) {
                $this->data[$datum[$this->keyField]] = $datum;
            }
        }
        return $this->data;
    }

    public function getField($key, $field, $defaultValue = '')
    {
        return Arr::get($this->getByKey($key), $field, $defaultValue);
    }

    public function getByKey($key)
    {
        return Arr::get($this->data, $key, []);
    }
}